from fastapi import APIRouter, Depends, Query, Request
from starlette.responses import HTMLResponse
from tortoise.transactions import atomic

from applications.common.render_template import templates
from applications.common.user_manager import permission_depends
from applications.utils.http import PageResponse, ResultResponse, fail_api, success_api, table_api
from applications.models import Dept, User
from applications.schemas.admin_dept import (
    DeptEnableDisableSchema,
    DeptOut,
    DeptSaveSchema,
    DeptSchema,
    DeptUpdateSchema,
    DeptTree,
)

route = APIRouter(prefix="/dept", tags=["系统管理-部门管理"])


@route.get(
    "/",
    dependencies=[Depends(permission_depends("system:dept:main"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def main(request: Request):
    return templates.TemplateResponse("system/dept/main.html", {"request": request})


@route.post(
    "/data",
    summary="获取部门列表",
    dependencies=[Depends(permission_depends("system:dept:main"))],
    response_model=PageResponse[DeptTree],
)
async def get_dept_list():
    depts = await Dept.all().order_by("sort")
    data = [DeptSchema.model_validate(dept).model_dump() for dept in depts]

    # 创建一个字典，用于存储每个节点的子节点
    tree = {}
    for item in data:
        item["children"] = []
        tree[item["id"]] = item

    # 构建树形结构
    root_nodes = []
    for item in data:
        parent_id = item["parent_id"] if item["parent_id"] != 0 else None
        if parent_id is None:
            root_nodes.append(item)
        else:
            if parent_id in tree:
                tree[parent_id]["children"].append(item)

    return table_api(msg="请求成功", data=root_nodes)


@route.get(
    "/add",
    dependencies=[Depends(permission_depends("system:dept:add"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def add(request: Request):
    return templates.TemplateResponse("system/dept/add.html", {"request": request})


@route.get(
    "/tree",
    response_model=DeptOut,
    dependencies=[Depends(permission_depends("system:dept:main"))],
    summary="获取部门树",
)
async def tree():
    dept = await Dept.all()
    res = {"status": {"code": 200, "message": "默认"}, "data": dept}
    return res


# 保存部门
@route.post(
    "/save",
    summary="保存部门",
    response_model=ResultResponse,
    dependencies=[Depends(permission_depends("system:dept:add"))],
)
async def save(data: DeptSaveSchema):
    # 直接使用model_dump(by_alias=True)来获取使用别名的字典
    dept_data = data.model_dump()
    dept = Dept(**dept_data)
    await dept.save()
    return success_api(msg="添加部门成功")


# 编辑部门
@route.get(
    "/edit",
    dependencies=[Depends(permission_depends("system:dept:edit"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def edit(request: Request, dept_id: int = Query(..., title="部门ID", alias="deptId")):
    dept = await Dept.get_or_none(id=dept_id)
    if not dept:
        return fail_api(msg="部门不存在")
    return templates.TemplateResponse("system/dept/edit.html", {"request": request, "dept": dept})


# 更新部门
@route.put(
    "/update",
    dependencies=[Depends(permission_depends("system:dept:edit"))],
    summary="更新部门",
    response_model=ResultResponse,
)
async def update(data: DeptUpdateSchema):
    # 直接使用model_dump(by_alias=True)来获取使用别名的字典，排除id字段
    dept_data = data.model_dump(by_alias=True, exclude={"deptId", "parentId"})

    dept = await Dept.get_or_none(id=data.deptId)
    if not dept:
        return fail_api(msg="部门不存在")

    for key, value in dept_data.items():
        if hasattr(dept, key):
            setattr(dept, key, value)

    await dept.save()
    return success_api(msg="更新部门成功")


# 启用部门
@route.put(
    "/enable",
    dependencies=[Depends(permission_depends("system:dept:edit"))],
    summary="启用部门",
    response_model=ResultResponse,
)
async def enable(data: DeptEnableDisableSchema):
    dept = await Dept.get_or_none(id=data.deptId)
    if not dept:
        return fail_api(msg="部门不存在")

    dept.status = 1
    await dept.save()
    return success_api(msg="启用部门成功")


# 禁用部门
@route.put(
    "/disable",
    dependencies=[Depends(permission_depends("system:dept:edit"))],
    summary="禁用部门",
    response_model=ResultResponse,
)
async def dis_enable(data: DeptEnableDisableSchema):
    dept = await Dept.get_or_none(id=data.deptId)
    if not dept:
        return fail_api(msg="部门不存在")

    dept.status = 0
    await dept.save()
    return success_api(msg="禁用部门成功")


# 删除部门
@route.delete(
    "/remove/{pk}",
    dependencies=[Depends(permission_depends("system:dept:remove"))],
    summary="删除部门",
    response_model=ResultResponse,
)
@atomic()
async def remove(pk: int):
    dept = await Dept.get_or_none(id=pk)
    if not dept:
        return fail_api(msg="部门不存在")

    # 将该部门下的用户部门ID设为None
    await User.filter(dept_id=pk).update(dept_id=None)

    await dept.delete()
    return success_api(msg="删除部门成功")


# 批量删除部门
@route.delete(
    "/batchRemove",
    dependencies=[Depends(permission_depends("system:dept:remove"))],
    summary="批量删除部门",
    response_model=ResultResponse,
)
@atomic()
async def batch_remove(ids: list[int]):
    if not ids:
        return fail_api(msg="未提供删除 ID")

    # 将这些部门下的用户部门ID设为None
    await User.filter(dept_id__in=ids).update(dept_id=None)

    # 删除部门
    await Dept.filter(id__in=ids).delete()

    return success_api(msg="批量删除成功")
